import json
import geocode
import requests
import time


def get_transit_route(origin: str, destination: str, strategy: int = 0, alternative_route: int = 5, tool: bool = False):
    """
    公共交通路线规划。
    :param origin: 起点结构化地址信息，例如“北京市朝阳区阜通东大街6号”。
    :param destination: 目的地结构化地址信息，例如“北京市朝阳区阜通东大街6号”。
    :param strategy: 0：推荐模式，综合权重，同高德APP默认 1：最经济模式，票价最低 2：最少换乘模式，换乘次数少 3：最少步行模式，尽可能减少步行距离 4：最舒适模式，尽可能乘坐空调车
                    5：不乘地铁模式，不乘坐地铁路线 7：地铁优先模式，步行距离不超过4KM 8：时间短模式，方案花费总时间最少。
    :param alternative_route: 返回方案条数，默认为5。
    :param tool: 截断生成
    :return: 格式化后的公交路线规划结果。
    """
    print("已调用get_transit_route")
    try:
        time.sleep(1)
        ORI = geocode.geocode(address=origin)
        DES = geocode.geocode(address=destination)
        if isinstance(ORI, str):
            print(ORI)
            ORI = json.loads(ORI)
        if isinstance(DES, str):
            print(DES)
            DES = json.loads(DES)
        # 构造请求参数
        params = {
            "key": '15b4ad5020694dbd091886d7d9d24bb9',
            "origin": ORI['location'],
            "destination": DES['location'],
            "city1": ORI['citycode'],
            "city2": DES['citycode'],
            "strategy": strategy,
            "alternative_route": alternative_route
        }

        # 发送请求
        response = requests.get("https://restapi.amap.com/v5/direction/transit/integrated", params=params)
        response.raise_for_status()  # 检查请求是否成功
        data = response.json()

        # 格式化结果
        if data["status"] == "1" and data["infocode"] == "10000":
            routes = data["route"]["transits"][0]
            formatted_routes = []
            distance = routes["distance"]
            walking_distance = routes["walking_distance"]
            if tool is True:
                return distance
            formatted_routes.append(f'本条路线的总距离为{distance}米\n总步行距离为{walking_distance}米\n')
            segments = routes["segments"]
            for segment in segments:
                if "'walking':" in str(segment):
                    for step in segment['walking']['steps']:
                        formatted_routes.append(f"{step['instruction']}")
                if "'bus':" in str(segment):
                    for busline in segment['bus']['buslines']:
                        formatted_routes.append(
                            f"乘坐{busline['name']}\n起始站：{busline['departure_stop']['name']}\n终点站："
                            f"{busline['arrival_stop']['name']}\n途经站点:")

                        for stop in busline["via_stops"]:
                            if stop['name']:
                                formatted_routes.append(f"{stop['name']}")
                        formatted_routes.append(f"共计{int(busline['via_num']) + 1}站")
                if "'railway':" in str(segment):
                    railway = segment['railway']
                    formatted_routes.append(
                        f"乘坐{railway['name']}\n起始站：{railway['departure_stop']['name']}\n终点站："
                        f"{railway['arrival_stop']['name']}\n座位类型及票价：")
                    for seat in railway["spaces"]:
                        formatted_routes.append(f"{seat['code']}：{seat['cost']}元")
                if "'taxi':" in str(segment):
                    formatted_routes.append(segment['taxi'])
            return "\n".join(formatted_routes)
        else:
            return f"Error: {data.get('info', '未知错误')}"
    except requests.exceptions.RequestException as e:
        return f"Error fetching transit route: {e}"